package com.dmgameclient.fragments;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;

import com.dmgameclient.R;
import com.dmgameclient.activities.DetailArticleActivity;
import com.dmgameclient.adapter.ArticleListViewAdapter;
import com.dmgameclient.beans.Article;
import com.dmgameclient.common.HttpUtils;
import com.dmgameclient.common.JsonUtils;
import com.dmgameclient.common.UIHelper;
import com.dmgameclient.common.URLHelper;
import com.dmgameclient.widget.OnLoadMoreListener;
import com.dmgameclient.widget.OnRefreshListener;
import com.dmgameclient.widget.PullListView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * @name ContentFragment1
 * @Descripation <br>
 *               1、文章列表页面为复用页面，须声明一个type进行标记。<br>
 *               2、<br>
 * @author 樊俊彬
 * @date 2014-9-19
 * @version 1.0
 */

@SuppressLint("ValidFragment")
public class FragmentArticle extends Fragment {

	private static final String TAG = "FragmentArticle";
	private PullListView listView;
	private ArticleListViewAdapter adapter;
	public List<Article> list = new ArrayList<Article>();
	private Handler handler;

	// 请求时文章类型和分页页数
	private String typeId;
	private int page = 1;

	public FragmentArticle() {
	}

	public FragmentArticle(Bundle bundle) {
		typeId = bundle.getString("type");
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Log.i(TAG, ">>>FragmentArticle---onCreate");
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.i(TAG, ">>>FragmentArticle---onCreateView");
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_article_listview,
				container, false);
		listView = (PullListView) view.findViewById(R.id.articleListView);
		initFrame();
		return view;
	}

	/**
	 * 页面主要逻辑
	 */
	@SuppressLint("HandlerLeak")
	private void initFrame() {
		adapter = new ArticleListViewAdapter(getActivity(),
				R.layout.item_listview_article, list, listView);
		listView.setAdapter(adapter);

		// 根据不同的操作刷新页面
		handler = new Handler() {
			@SuppressWarnings("unchecked")
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				// 数据下载成功
				if (msg.obj != null) {
					switch (msg.arg1) {
					case UIHelper.ACTION_TYPE_INIT:
						list.clear();
						listView.onRefreshComplete();
						break;

					case UIHelper.ACTION_TYPE_REFRESH:
						list.clear();
						listView.onRefreshComplete("最近更新:"
								+ new Date().toLocaleString());
						listView.setSelection(0);
						break;
					case UIHelper.ACTION_TYPE_LOADMORE:
						listView.onLoadMoreComplete("上拉加载更多");
						listView.setSelection(0);
						break;
					}
					list.addAll((List<Article>) msg.obj);
					adapter.notifyDataSetChanged();
				}
			}
		};

		// 初始化不作任何操作加载第1页数据
		loadData(typeId, 1, UIHelper.ACTION_TYPE_INIT);

		// 下拉刷新时加载第1页数据
		listView.setOnRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				loadData(typeId, 1, UIHelper.ACTION_TYPE_REFRESH);
			}
		});

		// 列表滚动到底部时依次加载第2、3、4...分页数据
		listView.setOnLoadMoreListener(new OnLoadMoreListener() {
			@Override
			public void onLoadMore() {
				// TODO Auto-generated method stub
				loadData(typeId, ++page, UIHelper.ACTION_TYPE_LOADMORE);
			}
		});

		// 点击列表项
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// 传递当前对象到文章详细页面
				Intent intent = new Intent(getActivity(),
						DetailArticleActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("articleObject", list.get(position - 1));
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
	}

	/**
	 * 启动线程、下载数据、解析结果返回界面
	 * 
	 * @param type
	 * @param page
	 */
	public void loadData(final String type, final int page, final int actionType) {
		// 下载文章列表数据
		Executors.newSingleThreadExecutor().execute(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Message msg = Message.obtain();
				msg.arg1 = actionType;
				msg.obj = JsonUtils.parseArticleList(HttpUtils.downloadString(
						URLHelper.getArticleListUrl(type, page),
						URLHelper.ENCODE));
				handler.sendMessage(msg);
			}
		});
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
}
